package com.impress.adapter;

import java.util.List;

import com.impress.MainListActivity;
import com.impress.R;
import com.impress.model.Feed;
import com.impress.model.Item;
import com.impress.service.FeedService;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FeedListAdapter extends BaseAdapter {

	public static final String REMOVE_ITEMS = FeedListAdapter.class.getName()+".REMOVE_ITEMS";
	public static final String SELECTED_POSITION = "SELECTED_POSITION";
	private Context mContext;
	public List<Feed> mFeeds;

	public FeedListAdapter(Context context, List<Feed> feeds) {
		this.mContext = context;
		this.mFeeds = feeds;
	}

	@Override
	public int getCount() {

		return this.mFeeds.size();
	}

	@Override
	public Object getItem(int position) {
		Feed feed = mFeeds.get(position);
		return feed;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		final Feed feed = mFeeds.get(position);
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.snippet, null);
			holder = new ViewHolder();
			holder.textView = (TextView) convertView
					.findViewById(R.id.item_title);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.mark_as_read);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.textView.setText(feed.getTitle());
		holder.imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(mContext instanceof MainListActivity){
					((MainListActivity)mContext).showDialog(MainListActivity.MARK_ALL_AS_READ, 
							feed,position);
				}
//				markAllAsRead(feed);
//				Intent intent = new Intent(REMOVE_ITEMS);
//				intent.putExtra(SELECTED_POSITION, position);
//				mContext.sendBroadcast(intent);
			}
		});
		// holder.imageView.setVisibility(View.VISIBLE);
		// List<Item> items = mItemService.getItemsByFeed(feed.getAtomID());
		return convertView;
	}

	class ViewHolder {
		TextView textView;
		ImageView imageView;
	}
	
	private void markAllAsRead(final Feed feed){
		if(mFeeds.contains(feed)){
			mFeeds.remove(feed);
			notifyDataSetChanged();
		}
		new Thread(){
			@Override
			public void run() {
				FeedService.markAllAsRead(mContext, feed);
			}			
		}.start();
	}

}
